const app = getApp();

/**
 * header
 */
interface IHeader {
  'Content-Type': string;
  device: string;
  authorization?: string;
}

interface IResponseData {
  code: number;
  message: string;
  result: any;
  status: number;
  success: boolean;
}

interface IResponse {
  cookies: string[],
  data: IResponseData;
  errMsg: string;
  header: any;
  statusCode: number;
}

export default class RequestUtil {

  /**
   * 实例化
   */
  static newInstance() {
    return new RequestUtil();
  }

  /**
   * 获取请求头
   */
  private static getHeader() {
    // header form-data
    const header: IHeader = {
      'Content-Type': 'application/x-www-form-urlencoded',
      device: 'weapp',
    };

    // header 中加入token
    const { token } = app.globalData;
    if (token) {
      header.authorization = `Bearer ${ token }`;
    }

    return header;
  }

  /**
   * 处理回调
   * @param method
   * @param url
   * @param data
   */
  private processRequest(method: any, url: string, data: any) {
    // header form-data
    const header = RequestUtil.getHeader();

    return new Promise((resolve: any, reject: any) => {
      // 请求
      wx.request({
        url,
        data,
        method,
        header,
        success: resolve,
        fail: reject,
      });
    }).then((res: any) => {
      const r: IResponse = res;
      return Promise.resolve(r.data);
    }).catch((err: any) => {
      return Promise.reject(err.data)
    });
  }


  public get(url: string, data: any) {
    return this.processRequest('GET', url, data);
  }

  public post(url: string, data: any) {
    return this.processRequest('POST', url, data);
  }
}

export { RequestUtil };
